<template>
  <!-- 商户管理页面 -->
  <div class="merchant-page" :style="{ height: '100vh' }">

    <!-- 固定在顶部的UI -->
    <div class="fixed-header" v-if="showFixedHeader" :style="{ height: capsuleTop + 40 + 'px' }">
      <div class="fixed-header-content">
        <div class="fixed-back-btn" @click="goBack">返回</div>
        <div class="fixed-title">{{ shopInfo.shopName }}</div>
      </div>
    </div>

    <div class="home-page-capsule h-200rpx " :style="{ height: capsuleHeight + 'px', top: capsuleTop + 'px' }"
      @click="goBack">
      <!-- 你的胶囊按钮内容 -->
      返回
    </div>
    <div class="home-page-banner">
      <img
        :src="shopInfo?.shopExtendsJson?.bannerInfo ? shopInfo?.shopExtendsJson?.bannerInfo : '../static/imgs/banner.png'"
        alt="">
    </div>
    <div class="merchant-logo">
      <img class="logo-img" :src="shopInfo.logo" alt="">
      <div class="merchant-logo-title">
        <div>{{ shopInfo.shopName }}</div>
        <div @click="handlerGotoR" style="color: #1677ff;"> 《商家入驻协议》</div>
      </div>
      <!-- 替换收藏按钮为两个操作按钮 -->
      <div class="operation-buttons">
        <!-- <div class="op-btn" :class="{
          'auto-accept-on': autoAcceptOrder,
          'auto-accept-off': !autoAcceptOrder
        }" @click="toggleAutoAccept">
          <span>{{ autoAcceptOrder ? '自动接单中' : '自动接单' }}</span>
        </div> -->

        <!-- 营业状态按钮 -->
        <div class="op-btn" :class="{
          'business-open': isBusinessOpen,
          'business-closed': !isBusinessOpen
        }" @click="toggleShopStatus">
          <span>{{ isBusinessOpen ? '营业中' : '已打烊' }}</span>
        </div>

        <!-- 配送订单按钮  -->
        <div  class="op-btn delivery-btn" @click="goToDeliveryOrders">
          <span>配送订单</span>
        </div>
        <div v-if="showEmployee" class="op-btn delivery-btn" @click="goToEmployee">
          <span>员工</span>
        </div>
      </div>
    </div>
    <div class="merchant-classification">
      <div class="merchant-classification-header">
        <div class="header-item" :class="{ active: activeTab === 'order' }" @click="switchTab('order')">点餐</div>
      </div>
      <div class="merchant-classification-content" v-if="activeTab === 'order'">
        <div class="content-left" style="height: 1200rpx; overflow-y: auto;box-sizing: border-box;">
          <template v-for="(category, index) in categories" :key="index">
            <div class="content-left-item" :class="{ active: activeCategory === index }"
              @click="switchCategory(category, index)">
              <img :src="category.icon" alt="">
              <div>{{ category.categoryName }}</div>
            </div>
          </template>
        </div>
        <scroll-view class="content-right" scroll-y style="height: 1200rpx;">
          <template v-for="(category, categoryIndex) in categories" :key="categoryIndex">
            <div class="content-right-item" v-if="activeCategory === categoryIndex">
              <div class="item-title">
                <div>{{ category.categoryName }}</div>
              </div>
              <div class="item-content">
                <template v-if="category.products && category.products.length > 0">
                  <template v-for="(product, productIndex) in category.products" :key="productIndex">
                    <div class="item-content-item">
                      <img :src="product.thumbnail" alt="">
                      <div class="item-content-item-title">
                        <div class="one">{{ product.goodsName }}</div>
                        <!-- <div class="two">月销 {{ product.monthlySales }}</div> -->
                        <!-- <div class="three">近期购买人数 {{ product.recentBuyers }}</div> -->
                        <div class="four">
                          <div class="four-left">
                            <span>￥</span>
                            <span>{{ product.listGoodsSkus?.[0]?.priceStr || product.listGoodsSkus?.[0]?.marketPrice ||
                              0
                              }}</span>
                          </div>
                          <div class="four-right">
                            <div @click.stop="handlerProductStatus(product)" class="four-right-copyof"
                              :class="getProductStatusClass(product)">
                              {{ getProductStatus(product) }}
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  </template>
                </template>
                <template v-else>
                  <div class="item-content-item-wu">
                    <img src="../static/imgs/zanwu.png" alt="">
                    <div class="text">暂无商品</div>
                  </div>
                </template>
              </div>
            </div>
          </template>
        </scroll-view>
      </div>
      <div class="merchant-classification-content" v-else>
        <!-- 商家信息内容 -->
        <div style="padding: 40rpx; text-align: center; color: #999;">
          {{ shopInfo.remark }}
        </div>
      </div>
    </div>



  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import bottomNav from '@/components/bottomNav.vue'

const capsuleHeight = ref(0)
const capsuleTop = ref(0)
const isSearchFixed = ref(false)
const value = ref('')
const scrollTop = ref(0)
const searchInputRef = ref(null)
const isCollected = ref(false)
const activeTab = ref('order')
const activeCategory = ref(0)
const showFixedHeader = ref(false)

// 分类数据
const categories = ref([])
const shopInfo = ref({})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const toggleCollect = () => {
  isCollected.value = !isCollected.value
  uni.showToast({
    title: isCollected.value ? '已收藏' : '已取消收藏',
    icon: 'success'
  })
}

const switchTab = (tab) => {
  activeTab.value = tab
}

const switchCategory = (category, index) => {
  activeCategory.value = index
  categoryId.value = category.categoryId
  getMerchantGoods(category.categoryId)
}

const showEmployee = ref(true)
onShow(() => {
  const userInfo = JSON.parse(uni.getStorageSync('config-user'))
  console.log(userInfo, 'userInfo');
  if (userInfo.user.roleTypeId == 4) {
    showEmployee.value = false
  }
})

// 使用节流函数来优化性能
let scrollTimer = null
const handleScroll = (e) => {
  if (scrollTimer) {
    clearTimeout(scrollTimer)
  }

  scrollTimer = setTimeout(() => {
    const scrollTopValue = e.detail.scrollTop
    scrollTop.value = scrollTopValue
    console.log('滚动位置:', scrollTopValue)

    // 当滚动距离超过170px时显示固定头部，但不阻止滚动
    showFixedHeader.value = scrollTopValue > 170

    // #ifdef MP-WEIXIN
    const query = uni.createSelectorQuery()
    query.select('.search-input').boundingClientRect((rect) => {
      if (rect) {
        console.log('搜索框位置:', rect.top, '胶囊底部位置:', capsuleTop.value + capsuleHeight.value)
        // 当搜索框顶部位置小于等于胶囊按钮底部位置时，显示固定搜索框
        isSearchFixed.value = rect.top <= (capsuleTop.value + capsuleHeight.value)
      }
    }).exec()
    // #endif
  }, 16) // 约60fps的刷新率
}
// 店铺id
const shopId = ref('')
// 店铺商品分类选择id
const categoryId = ref('')
// 商品id
const goodsId = ref('')

onLoad((options) => {
  console.log(options)
  shopId.value = options.shopId
  categoryId.value = options.categoryId
  goodsId.value = options.goodsId
  getMerchantInfo()
  getMerchantClassification()
})
// 计算店铺是否营业
const isBusinessOpen = computed(() => {
  return shopInfo.value.businessStatus === 1
})
// 店铺详情
const getMerchantInfo = async () => {
  const res = await Fetch(`shopping/shopInfo/${shopId.value}`, {
    method: 'get',
  })
  if (res.data.code === 200) {
    const extendsJson = JSON.parse(res.data.data.extendsJson)
    res.data.data.shopExtendsJson = extendsJson
    shopInfo.value = res.data.data
  } else {
    uni.showToast({
      title: res.data.msg,
      icon: 'none',
    })
  }
}

// 店铺商品分类
const getMerchantClassification = async () => {
  const res = await Fetch(`shopping/goodsCategory/list`, {
    method: 'get',
    data: {
      shopId: shopId.value,
      pageSize: 100,
    }
  })
  if (res.data.code === 200) {
    if (res.data.rows.length > 0) {
      categories.value = res.data.rows
      if (categoryId.value) {
        // 如果传入商品分类id，则选中该分类
        categories.value.forEach((item, index) => {
          if (item.categoryId === categoryId.value) {
            activeCategory.value = index
          }
        })
        getMerchantGoods(categoryId.value)
        return
      } else {
        categoryId.value = categories.value[activeCategory.value]?.categoryId
        getMerchantGoods(categories.value[activeCategory.value]?.categoryId || '')
      }
    }

  } else {
    uni.showToast({
      title: res.data.msg,
      icon: 'none',
    })
  }
}

// 店铺商品分类下的商品
const getMerchantGoods = async (categoryId) => {
  const res = await Fetch(`shopping/goodsInfo/list`, {
    method: 'get',
    data: {
      shopId: shopId.value,
      categoryId: categoryId,
      page: 1,
      pageSize: 1000
    }
  })
  if (res.data.code === 200) {
    categories.value[activeCategory.value].products = res.data.rows
  } else {
    uni.showToast({
      title: res.data.msg,
      icon: 'none',
    })
  }
}

// 仅保留上架/下架逻辑
const getProductStatus = (product) => {
  return product.isShelves === 1 ? '下架' : '上架'
}

const getProductStatusClass = (product) => {
  return product.isShelves === 1 ? 'off-shelf' : 'on-sale'
}

// 商品上下架
const handlerProductStatus = async (product) => {
  console.log(product, '???');
  const res = await Fetch('shopping/goodsInfo/edit', {
    method: 'put',
    data: {
      goodsId: product.goodsId,
      isShelves: product.isShelves == 1 ? 2 : 1
    }
  })

  if (res.data.code == 200) {
    uni.showToast({
      title: res?.data?.msg,
      icon: 'success'
    })
    getMerchantGoods(categoryId.value)
  } else {
    uni.showToast({
      title: res?.data?.msg,
      icon: 'none'
    })
  }
}

// 自动接单状态
const autoAcceptOrder = ref(false)
// 店铺营业状态
const shopClosed = ref(false)

// 前往商家入驻协议
const handlerGotoR = () => {
  uni.navigateTo({ url: '/pages-shift/MerchantEntry' })
}

// 切换自动接单
const toggleAutoAccept = async () => {
  try {
    const result = await Fetch('shopping/shop/toggleAutoAccept', {
      method: 'POST',
      data: {
        autoAccept: !autoAcceptOrder.value
      }
    })

    if (result.data.code === 200) {
      autoAcceptOrder.value = !autoAcceptOrder.value
      uni.showToast({
        title: autoAcceptOrder.value ? '已开启自动接单' : '已关闭自动接单',
        icon: 'none'
      })
    }
  } catch (error) {
    uni.showToast({
      title: '操作失败',
      icon: 'none'
    })
  }
}

// 切换店铺营业状态
const toggleShopStatus = async () => {
  uni.showModal({
    title: isBusinessOpen.value ? '确认打烊' : '开启营业',
    content: isBusinessOpen.value ? '打烊后将不再接收新订单，是否确认？' : '是否确认开启营业？',
    success: async (res) => {
      if (res.confirm) {
        try {
          const result = await Fetch('shopping/shopInfo/edit', {
            method: 'put',
            data: {
              shopId: shopInfo.value.shopId,
              businessStatus: isBusinessOpen.value ? 0 : 1 // 切换状态
            }
          })

          if (result.data.code === 200) {
            // 更新店铺状态
            getMerchantInfo()
            uni.showToast({
              title: isBusinessOpen.value ? '已打烊' : '已开启营业',
              icon: 'success'
            })
          }
        } catch (error) {
          uni.showToast({
            title: '操作失败',
            icon: 'none'
          })
        }
      }
    }
  })
}

// 前往配送订单页面
const goToDeliveryOrders = () => {
  uni.navigateTo({ url: `/pages-shift/ShopDeliveryOrder?shopId=${shopId.value}&showEmployee=${showEmployee.value}` })
}

onMounted(() => {
  // #ifdef MP-WEIXIN
  const menuButtonInfo = wx.getMenuButtonBoundingClientRect()
  capsuleHeight.value = menuButtonInfo.height
  capsuleTop.value = menuButtonInfo.top
  console.log('胶囊按钮信息:', menuButtonInfo)
  // #endif
})

onPageScroll((e) => {
  const scrollTopValue = e.scrollTop
  console.log(e.scrollTop, 'e');
  // 当滚动距离超过170px时显示固定头部，但不阻止滚动
  showFixedHeader.value = scrollTopValue > 140
  const query = uni.createSelectorQuery()
  query.select('.search-input').boundingClientRect((rect) => {
    if (rect) {
      console.log('搜索框位置:', rect.top, '胶囊底部位置:', capsuleTop.value + capsuleHeight.value)
      // 当搜索框顶部位置小于等于胶囊按钮底部位置时，显示固定搜索框
      isSearchFixed.value = rect.top <= (capsuleTop.value + capsuleHeight.value)
    }
  }).exec()

})

const goToEmployee = () => {
  uni.navigateTo({ url: `/pages/EmployeeList?shopId=${shopId.value}` })
}

</script>

<style lang="scss" scoped>
.merchant-page {
  background: #F5F5F5;

  // 固定头部样式
  .fixed-header {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 88rpx;
    background: #FFFFFF;
    z-index: 999;
    box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    display: flex;
    align-items: flex-end;
    padding: 0 32rpx;
    box-sizing: border-box;
    pointer-events: none; // 添加这行，让固定头部不阻止滚动

    .fixed-header-content {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      padding-bottom: 10rpx;
      box-sizing: border-box;
      pointer-events: auto; // 恢复按钮的点击事件

      .fixed-back-btn {
        width: 120rpx;
        height: 60rpx;
        background: #F5F5F5;
        border-radius: 30rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 28rpx;
        color: #333;
        font-weight: 500;
        cursor: pointer; // 添加鼠标指针样式
      }

      .fixed-title {
        flex: 1;
        font-size: 32rpx;
        font-weight: bold;
        color: #191919;
        margin: 0 20rpx;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }
  }

  .home-page-capsule {
    position: fixed;
    left: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 100;
  }

  .home-page-banner {
    width: 750rpx;
    height: 500rpx;
    position: relative;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .merchant-logo {
    width: 702rpx;
    background: #FFFFFF;
    border-radius: 20rpx 20rpx 20rpx 20rpx;
    padding: 24rpx;
    box-sizing: border-box;
    margin: 0 auto;
    display: flex;
    align-items: self-start;
    position: relative;
    top: -100rpx;

    .logo-img {
      width: 136rpx;
      height: 136rpx;
      margin-right: 20rpx;
    }

    .merchant-logo-title {
      view {
        &:nth-child(1) {
          height: 50rpx;
          font-family: PingFang SC, PingFang SC;
          font-weight: bold;
          font-size: 36rpx;
          color: #191919;
          line-height: 50rpx;
          text-align: center;
          font-style: normal;
          text-transform: none;
          margin-bottom: 10rpx;
        }

        &:nth-child(2) {
          font-size: 22rpx;
          color: #999999;
        }
      }
    }

    .operation-buttons {
      display: flex;
      flex-direction: column;
      margin-left: auto;
      gap: 20rpx;

      .op-btn {
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 12rpx 20rpx;
        border-radius: 30rpx;
        font-size: 24rpx;
        cursor: pointer;
        text-align: center;
        transition: all 0.3s;
        min-width: 120rpx;
        font-weight: 500;

        // 自动接单开启状态
        &.auto-accept-on {
          background: #FFF7E6; // 浅橙色背景
          color: #FFA500; // 橙色文字
          border: 2rpx solid #FFA500; // 橙色边框
        }

        // 自动接单关闭状态
        &.auto-accept-off {
          background: #F5F5F5; // 浅灰色背景
          color: #999999; // 灰色文字
          border: 2rpx solid #DDDDDD; // 灰色边框
        }

        // 营业中状态
        &.business-open {
          background: #E8F5E9; // 浅绿色背景
          color: #4CAF50; // 绿色文字
          border: 2rpx solid #4CAF50; // 绿色边框
        }

        // 打烊状态
        &.business-closed {
          background: #FFE4E4; // 浅红色背景
          color: #FF4D4F; // 红色文字
          border: 2rpx solid #FF4D4F; // 红色边框
        }

        &:active {
          opacity: 0.8;
          transform: scale(0.98); // 添加轻微的缩放效果
        }
      }

      // 配送订单按钮样式
      .delivery-btn {
        background: #E6F4FF; // 浅蓝背景
        color: #1677FF; // 品牌蓝
        border: 2rpx solid #1677FF;
      }
    }
  }

  .merchant-classification {
    margin-top: -70rpx;
    background: white;

    .merchant-classification-header {
      height: 118rpx;
      display: flex;
      align-items: center;
      padding: 24rpx;
      box-sizing: border-box;

      .header-item {
        height: 44rpx;
        font-weight: bold;
        font-size: 32rpx;
        color: #000000;
        line-height: 44rpx;
        text-align: center;
        font-style: normal;
        text-transform: none;
        margin-right: 74rpx;
        position: relative;

        &.active {
          &::after {
            content: '';
            position: absolute;
            bottom: -10rpx;
            left: 50%;
            transform: translateX(-50%);
            width: 40rpx;
            height: 8rpx;
            background: #F9DC40;
            border-radius: 4rpx 4rpx 4rpx 4rpx;
          }
        }
      }
    }

    .merchant-classification-content {
      background: white;
      display: flex;

      .content-left {
        width: 162rpx;
        background: #F8F8F8;

        .content-left-item {
          height: 120rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 0rpx 20rpx 20rpx 0rpx;

          &.active {
            background: white;
            border-radius: 0rpx;
          }

          image {
            width: 24rpx;
            height: 26rpx;
          }
        }
      }

      .content-right {
        flex: 1;
        padding: 18rpx 24rpx;
        box-sizing: border-box;

        .content-right-item {
          .item-title {
            height: 44rpx;
            font-weight: bold;
            font-size: 32rpx;
            color: #000000;
            line-height: 44rpx;
            text-align: left;
            font-style: normal;
            text-transform: none;
            margin-bottom: 30rpx;

            label {
              height: 34rpx;
              font-weight: 400;
              font-size: 24rpx;
              color: #999999;
              line-height: 34rpx;
              text-align: center;
              font-style: normal;
              text-transform: none;
              margin-left: 10rpx;
            }
          }

          .item-content {
            .item-content-item {
              display: flex;
              margin-bottom: 40rpx;

              image {
                width: 158rpx;
                height: 158rpx;
                border-radius: 16rpx 16rpx 16rpx 16rpx;
                margin-right: 20rpx;
              }

              .item-content-item-title {
                flex: 1;
                width: 100%;

                .one {
                  font-weight: bold;
                  font-size: 28rpx;
                  color: #000000;
                  text-transform: none;
                }

                .two {
                  height: 34rpx;
                  font-weight: 400;
                  font-size: 24rpx;
                  color: #999999;
                  line-height: 34rpx;
                  text-transform: none;
                }

                .three {
                  height: 34rpx;
                  font-weight: 400;
                  font-size: 24rpx;
                  color: #999999;
                  line-height: 34rpx;
                  text-transform: none;
                }

                .four {
                  display: flex;
                  align-items: flex-end;
                  width: 100%;

                  .four-left {
                    margin-right: auto;
                    margin-bottom: 6rpx;
                    height: 44rpx;
                    font-weight: bold;
                    font-size: 32rpx;
                    color: #EA5838;
                    line-height: 44rpx;
                    text-transform: none;

                    label {
                      &:nth-child(1) {
                        height: 34rpx;
                        font-weight: bold;
                        font-size: 24rpx;
                        color: #EA5838;
                        line-height: 34rpx;
                        text-transform: none;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }

  .item-content-item-wu {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    margin: 60rpx auto;
    text-align: center;

    image {
      width: 281rpx;
      height: 213rpx;
    }

    .text {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: #999;
    }
  }

  .goods-status-btn {
    height: 46rpx;
    padding: 6rpx 18rpx;
    font-size: 24rpx;
    font-weight: bold;
    line-height: 46rpx;
    border-radius: 24rpx;
    text-align: center;

    &.status-sold-out {
      background: #CCCCCC;
      color: #FFFFFF;
    }

    &.status-off-shelf {
      background: #F2F2F2;
      color: #999999;
    }

    &.status-on-sale {
      background: #F9E149;
      color: #000000;
    }
  }

  .four-right-copyof {
    height: 46rpx;
    background: #F9E149;
    border-radius: 24rpx 24rpx 24rpx 24rpx;
    padding: 6rpx 18rpx;
    font-size: 24rpx;
    font-weight: bold;
    color: #000000;
    line-height: 46rpx;

    &.sold-out {
      background: #CCCCCC;
      color: #FFFFFF;
    }

    &.off-shelf {
      background: #F2F2F2;
      color: #999999;
    }

    &.on-sale {
      background: #F9E149;
      color: #000000;
    }
  }
}

/* 库存修改弹窗样式 */
.stock-popup {
  width: 600rpx;
  background: #FFFFFF;
  border-radius: 20rpx;
  padding: 30rpx;

  .stock-popup-title {
    font-size: 32rpx;
    font-weight: bold;
    text-align: center;
    padding-bottom: 20rpx;
    border-bottom: 1px solid #f5f5f5;
  }

  .stock-popup-content {
    padding: 20rpx 0;

    .product-info {
      margin-bottom: 20rpx;

      .product-name {
        font-size: 28rpx;
        font-weight: bold;
        margin-bottom: 10rpx;
      }

      .stock-details {
        display: flex;
        justify-content: space-around;
        flex-wrap: wrap;
        margin-top: 10rpx;

        .stock-item {
          font-size: 24rpx;
          color: #333;
          margin-bottom: 10rpx;

          &.available {
            color: #007bff;
            font-weight: bold;
          }
        }
      }
    }

    .stock-input {
      display: flex;
      align-items: center;
      margin-top: 20rpx;

      .input-label {
        font-size: 26rpx;
        color: #333;
        margin-right: 10rpx;
      }

      input {
        flex: 1;
        height: 70rpx;
        border: 1px solid #ddd;
        border-radius: 8rpx;
        padding: 0 20rpx;
        font-size: 26rpx;
      }
    }
  }

  .stock-popup-footer {
    display: flex;
    padding-top: 20rpx;
    border-top: 1px solid #f5f5f5;

    .cancel-btn,
    .confirm-btn {
      flex: 1;
      height: 80rpx;
      line-height: 80rpx;
      text-align: center;
      font-size: 28rpx;
      border-radius: 40rpx;
    }

    .cancel-btn {
      background: #f5f5f5;
      color: #666;
      margin-right: 20rpx;
    }

    .confirm-btn {
      background: #F9E149;
      color: #000;
    }
  }
}
</style>
